package com.fw.application.controller;


import com.alibaba.fastjson.JSON;
import com.alipay.api.AlipayApiException;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.fw.application.controller.base.BaseController;
import com.fw.common.AliComm;
import com.fw.common.IdXD;
import com.fw.constant.Constant;
import com.fw.enums.AliPayEnum;
import com.fw.enums.LogsModelEnum;
import com.fw.enums.LogsTypeEnum;
import com.fw.mes.Result;
import com.fw.system.web.model.entity.*;
import com.fw.system.web.model.form.SellShangJiaForm;
import com.fw.system.web.model.form.ShopIngShangJiaForm;
import com.fw.system.web.model.vo.DealVo;
import com.fw.system.web.model.vo.SellVo;
import com.fw.system.web.model.vo.ShangjiaDealVo;
import com.fw.system.web.service.IFwLogsService;
import com.fw.system.web.service.IFwMoneysService;
import com.fw.system.web.service.IFwShangjiaDealService;
import com.fw.system.web.service.IFwShangjiaService;
import com.fw.utils.uuid.UUID;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;

import static com.fw.mes.ResultUtils.success;

/**
 * <p>
 * 商甲交易,买卖表 前端控制器
 * </p>
 *
 * @author
 * @since 2021-06-08
 */
@RestController
@RequestMapping("/deal")
@Api(tags = "商甲交易相关")
@RequiredArgsConstructor
@Slf4j
public class FwShangjiaDealController implements BaseController {

    private final IdXD idXD;
    private final AliComm aliComm;
    private final IFwLogsService logsService;
    private final IFwMoneysService moneysService;
    private final IFwShangjiaService shangjiaService;
    private final IFwShangjiaDealService shangjiaDealService;

    @ApiOperation("shlo:商甲交易:交易明细")
    @GetMapping("listDetail")
    public Result<List<FwShangjiaDeal>> listDetail(@PathVariable FwShangjiaDeal fwShangjiaDeal) {
        //实体类可多条件查询，如需防止越权可固定相关条件
        List<FwShangjiaDeal> list = shangjiaDealService.list(Wrappers.lambdaQuery(fwShangjiaDeal));
        return success(list);
    }

    @ApiOperation("shlo:商甲交易:我要买")
    @GetMapping("/listShopIng")
    public Result<DealVo> listShopIng() {
        //获取当前登陆者信息
        FwUser user = getUser();
        //创建大vo集合
        DealVo dealVo = new DealVo();
        //获取卖出列表
        List<ShangjiaDealVo> dealList = shangjiaDealService.findDealList(Constant.ShopIngShangJiaType.IS_TYPE_ING.toString());
        //获取我的商甲余额
        FwMoneys moneys = moneysService.getOne(Wrappers.<FwMoneys>lambdaQuery().eq(FwMoneys::getUserId, user.getId()));
        BigDecimal shangJia = moneys.getShangJia();
        //获取市场价
        FwShangjia serviceOne = shangjiaService.getOne(Wrappers.<FwShangjia>lambdaQuery().eq(FwShangjia::getId, Constant.ShangJia.CONSUME_ID));
        BigDecimal presentPrice = serviceOne.getPresentPrice();

        //充实大vo
        dealVo.setShangjiaDealVos(dealList);
        dealVo.setMoneyShangJia(shangJia);
        dealVo.setPresentPrice(presentPrice);
        return success(dealVo);
    }

    @ApiOperation("shlo:购买商甲")
    @PostMapping("/ShopIngTrading")
    public synchronized Result ShopIngTrading(@RequestBody ShopIngShangJiaForm shopIngShangJiaForm) {

        String userId = getUser().getId();
        shopIngShangJiaForm.setUserId(userId);

        //验证
        FwShangjiaDeal deal = shangjiaDealService.getById(shopIngShangJiaForm.getId());
        if (shopIngShangJiaForm.getCount().compareTo(deal.getCount()) > 0 || deal.getIsLock().equals(1)) {
            return new Result().fail(0, "请稍后在购买");
        }
        deal.setIsLock(1);
        deal.setLockTime(LocalDateTime.now());
        shangjiaDealService.updateById(deal);
        /**
         * todo 调支付
         */
        try {
            String s = aliComm.appPay(UUID.randomUUID().toString().replace("-", ""),//阿里订单编号
                    shopIngShangJiaForm.getMoney(),
                    AliPayEnum.shop_Ing_Trading,
                    JSON.toJSONString(shopIngShangJiaForm)
            );
            return success(s);
        } catch (AlipayApiException e) {
            return new Result().fail(-1, "支付失败");
        }

    }

    @ApiOperation("shlo:卖出商甲(无需传id)")
    @PostMapping("/SellShangJia")
    public Result SellShangJia(@RequestBody SellShangJiaForm sellShangJiaForm) {
        //获取当前登陆者信息
        FwUser user = getUser();
        BigDecimal presentPrice = shangjiaService.getById("1").getPresentPrice();
        BigDecimal multiply = presentPrice.multiply(new BigDecimal("0.9"));
        if (sellShangJiaForm.getMoney().compareTo(multiply) < 0)
            return new Result().fail(0, "挂卖价格不能低于指导价的90%");
        if (StringUtils.isBlank(user.getAliPhone()) || StringUtils.isBlank(user.getAliUserName()))
            return new Result().fail(0, "请去绑定支付宝和支付宝名称");
        //验证商甲余额
        FwMoneys moneys = moneysService.getOne(Wrappers.<FwMoneys>lambdaQuery().eq(FwMoneys::getUserId, user.getId()));
        if (sellShangJiaForm.getCount().compareTo(moneys.getShangJia()) > 0) {
            return new Result().fail(0, "余额不足");
        }
        // 今日不可在卖出
        int dealCount = shangjiaDealService.count(Wrappers.<FwShangjiaDeal>lambdaQuery().eq(FwShangjiaDeal::getType, Constant.ShopIngShangJiaType.IS_TYPE_ING).eq(FwShangjiaDeal::getUserId, user.getId()).last("  and DATE_FORMAT(create_time,'%Y-%m-%d') = DATE_FORMAT(NOW(),'%Y-%m-%d') "));
        if (dealCount >= 1) {
            return new Result().fail(0, "今日商甲已卖出过,请明日在卖出.");
        }
        //新增商甲交易数据
        shangjiaDealService.save(new FwShangjiaDeal()
                .setId(idXD.nextId())
                .setCount(sellShangJiaForm.getCount())
                .setMoney(sellShangJiaForm.getMoney())
                .setType(Constant.ShopIngShangJiaType.IS_TYPE_ING)
                .setCreateTime(LocalDateTime.now())
                .setUserId(user.getId())
                .setCountJia(sellShangJiaForm.getCount())
        );
        //扣除当前持有商甲

        BigDecimal shangJia = moneys.getShangJia();
        BigDecimal count = sellShangJiaForm.getCount();
        BigDecimal subtract = shangJia.subtract(count);
        moneys.setShangJia(subtract);
        moneysService.updateById(moneys);
        return success();
    }

    @ApiOperation("shlo:商甲交易:买入记录")
    @GetMapping("/listShopIngLogs")
    public Result listShopIngLogs() {
        FwUser user = getUser();
        List<FwLogs> logs = logsService.list(Wrappers.<FwLogs>lambdaQuery()
                .eq(FwLogs::getBuiId, user.getId())
                .eq(FwLogs::getModelName, LogsModelEnum.SHANG_JIA_MODEL.getModelName())
                .eq(FwLogs::getIsType, LogsTypeEnum.MONEY_BUY.getTypeName())
        );
        return success(logs);
    }


    @ApiOperation("shlo:商甲交易:我要卖")
    @GetMapping("/listSell")
    public Result<SellVo> listSell() {
        //获取当前登陆者信息
        FwUser user = getUser();
        //创建大vo集合
        SellVo sellVo = new SellVo();
        //获取卖出记录
        /*List<FwLogs> logs = logsService.list(Wrappers.<FwLogs>lambdaQuery()
                .eq(FwLogs::getBuiId, user.getId())
                .eq(FwLogs::getModelName, LogsModelEnum.SHANG_JIA_MODEL.getModelName())
        );*/
        List<FwShangjiaDeal> list = shangjiaDealService.list(Wrappers.<FwShangjiaDeal>lambdaQuery()
                .eq(FwShangjiaDeal::getUserId, user.getId())
        );

        //获取我的商甲余额
        FwMoneys moneys = moneysService.getOne(Wrappers.<FwMoneys>lambdaQuery().eq(FwMoneys::getUserId, user.getId()));
        BigDecimal shangJia = moneys.getShangJia();
        //获取市场价
        FwShangjia serviceOne = shangjiaService.getOne(Wrappers.<FwShangjia>lambdaQuery().eq(FwShangjia::getId, Constant.ShangJia.CONSUME_ID));
        BigDecimal presentPrice = serviceOne.getPresentPrice();

        //充实大vo
        sellVo.setLogsList(list);
        sellVo.setMoneyShangJia(shangJia);
        sellVo.setPresentPrice(presentPrice);
        return success(sellVo);
    }

    @ApiOperation("姚:分红")
    @GetMapping("/bonus/{flag}")
    public Result bonus(@PathVariable Long flag) {
        log.info("分红开始了:{}", flag);
        //发出时的时间戳
        long l = flag ^ 3;
        //时间间隔大于5秒
        if (System.currentTimeMillis() - l > 5000) {
            log.info("时间间隔大于5秒,本轮不在执行");
            return success("时间间隔大于5秒");
        }
        shangjiaDealService.bonus();
        log.info("分红结束");
        return success();
    }


}

